package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.domain.OrderDetail;
import com.example.domain.Orders;
import com.example.dto.OrdersDto;
import com.example.service.OrderDetailService;
import com.example.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @GetMapping("/userPage")
    public R<Page<Orders>> page(Integer page,Integer pageSize){
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersService.page(ordersPage);
        return R.success(ordersPage);
    }

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 分页、查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page<OrdersDto>> getOrderDetailPage(Integer page, Integer pageSize, String number, LocalDateTime beginTime,LocalDateTime endTime){
        Page<Orders> pageList = new Page<Orders>(page, pageSize);
        ordersService.page(pageList,new LambdaQueryWrapper<Orders>()
                .like(StringUtils.isNotEmpty(number),Orders::getNumber,number)
        );

        Page<OrdersDto> ordersDtoPage=new Page<>();
        BeanUtils.copyProperties(pageList,ordersDtoPage,"records");
        List<OrdersDto> ordersDtos = pageList.getRecords().stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            List<OrderDetail> orderDetails = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, item.getNumber()));
            ordersDto.setOrderDetails(orderDetails);
            ordersDto.setUserName(ordersDto.getConsignee());
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }

    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        ordersService.updateById(orders);
        return R.success("状态更改成功");
    }
}
